<template>
    <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible" width="60%">
        <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
                 label-width="80px">
            <div class="flex-box">
                <div style="width: 53%">
                    <el-form-item label="培训名称" prop="title">
                        <el-input v-model="dataForm.title"></el-input>
                    </el-form-item>
                    <el-form-item label="组织机构" prop="institutional">
                        <el-input v-model="dataForm.institutional"></el-input>
                    </el-form-item>
                    <el-form-item label="培训目的" prop="goal">
                        <el-input v-model="dataForm.goal"></el-input>
                    </el-form-item>
                    <!--                  <el-form-item label="培训性质" prop="institutional">-->
                    <!--                    <el-input v-model="dataForm.institutional"></el-input>-->
                    <!--                  </el-form-item>-->
                    <el-form-item label="报名时间" prop="entryTime" required>
                        <el-date-picker
                                :disabled="disForm"
                                v-model="dataForm.entryTime"
                                type="datetimerange"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                change="entryTimeChange"
                        ></el-date-picker>
                    </el-form-item>
                    <el-form-item label="培训时间" prop="trainTime" required>
                        <el-date-picker
                                :disabled="disForm"
                                v-model="dataForm.trainTime"
                                type="datetimerange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                        ></el-date-picker>
                    </el-form-item>
                    <el-form-item label="授课老师" prop="trainTeacher">
                        <el-input v-model="dataForm.trainTeacher"></el-input>
                    </el-form-item>
                    <el-form-item label="培训地点" prop="trainPlace">
                        <el-input v-model="dataForm.trainPlace"></el-input>
                    </el-form-item>
                    <el-form-item label="授课课时" prop="trainHours">
                        <el-input v-model="dataForm.trainHours" :disabled="disForm" type="number">
                            <template slot="append">课时</template>
                        </el-input>
                    </el-form-item>
                </div>
                <div style="width: 46%">
                    <el-form-item label="封面" prop="mainImg">
                        <el-upload
                                :disabled="disForm"
                                :action="actionImg"
                                list-type="picture-card"
                                :on-success="handleImgSuccess"
                                :before-upload="beforeImgUpload"
                                :on-remove="handleImgRemove"
                                :on-exceed="handleExceed"
                                :file-list="dataForm.mainImgUrl"
                                :limit="1"
                        >
                            <i class="el-icon-plus"></i>
                        </el-upload>
                        <span class="el-upload__tip">小提示：建议上传大小为615*245</span>
                    </el-form-item>
                    <el-form-item label="排序" prop="sort">
                        <el-input v-model="dataForm.sort" :disabled="disForm" type="number"
                                  placeholder="数值越大越靠前"></el-input>
                        <span class="el-upload__tip">数值越大越靠前</span>
                    </el-form-item>
                    <!--<el-form-item label="关联考试" prop="sort">
                        <el-input v-model="dataForm.sort" :disabled="disForm" placeholder="数值越大越靠前">
                            <el-button type="text" slot="suffix" @click="relattionHandle">选择</el-button>
                        </el-input>
                    </el-form-item>-->
                </div>
            </div>
            <!--<el-form-item label="课程简介" prop="courseBrief">-->
            <!--<el-input  v-model="dataForm.courseBrief"></el-input>-->
            <!--</el-form-item>-->
            <el-form-item label="培训计划">
                <div v-for="(item,index,arr) in dataForm.plan" :key="index"
                     style="display: flex;flex-direction: row;margin-bottom: 10px;width:100%;align-items: center">
                    <el-input
                            v-model="item.val"
                            :disabled="disForm"
                            placeholder="请填写培训安排,例：2019-08-01,上午8:00-12:00充灯工安全操作规范培训,下午15:00-17:00充灯工日常工作规范"
                    ></el-input>
                    <el-button
                            :disabled="disForm"

                            type="primary"
                            icon="el-icon-delete"
                            circle
                            v-if="dataForm.plan.length > 1"
                            style="margin-left: 10px"
                            @click="removeValue(index)"
                    ></el-button>
                    <el-button
                            :disabled="disForm"

                            icon="el-icon-plus"
                            circle
                            v-if="index == dataForm.plan.length- 1"
                            style="margin-left: 10px"
                            @click="addValue"
                    ></el-button>
                    <!-- <i class="el-icon-delete" v-if="dataForm.trainingPlan.length > 1" style="margin-left: 10px" @click="removeOption(index)"></i>
                    <i class="el-icon-plus" v-if="index == dataForm.trainingPlan.length- 1" style="margin-left: 10px" @click="removeOption(index)"></i>-->
                </div>
            </el-form-item>
            <el-form-item label="参与人员" prop="trainType">
                <el-radio-group v-model="dataForm.trainType" @change="typeChange">
                    <el-radio :disabled="disForm" :label="0">全员参加</el-radio>
                    <el-radio :disabled="disForm" :label="1">按部门参与</el-radio>
                    <el-radio :disabled="disForm" :label="2">按人员参与</el-radio>
                </el-radio-group>
                <el-button
                        :disabled="disForm"
                        v-if="dataForm.trainType == 2"
                        typeof="primary"
                        style="margin-left: 20px"
                        @click="handlerOpenUserDialog"
                >选择参与人员
                </el-button>
                <el-form-item prop="deptIds" v-if="dataForm.trainType == 1">
                    <el-cascader :disabled="disForm" :options="deptList" filterable
                                 :props="deptListTreeProps" v-model="dataForm.deptIds" clearable placeholder="请选择参与部门"/>
                </el-form-item>
                <el-form-item prop="userList" v-if="dataForm.trainType == 2">
                    <el-table
                            :data="dataForm.userList"
                            @selection-change="handleSelectionChange"
                            max-height="300"
                    >
                        <el-table-column type="index" label="序号" width="80" align="center"/>
                        <el-table-column property="realname" label="姓名" width="200"/>
                        <el-table-column property="deptName" label="部门"/>
                        <el-table-column property="gender" label="性别">
                            <template slot-scope="scope">
                                <el-tag v-if="parseInt(scope.row.gender) === 1">男</el-tag>
                                <el-tag v-else>女</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column>
                            <template slot-scope="scope">
                                <el-button type="text" :disabled="disForm"
                                           @click="deleteHandle(scope.$index)">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item>
            </el-form-item>
            <el-form-item label="培训内容">
                <div style="margin-bottom: 20px;">
                    <ck-kditor @change="editorChange" ref="ckEditor"></ck-kditor>
                </div>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="visible = false">取消</el-button>
            <el-button type="primary" @click="dataFormSubmit()" :loading="loading || uploadLoading">确定</el-button>
        </div>

        <el-dialog title="人员列表" :visible.sync="dialogUserVisible" append-to-body>
            <el-form :inline="true" :model="dataForm" :disabled="disForm"
                     @keyup.enter.native="getDataList()">
                <el-form-item>
                    <el-input v-model="dataForm.realname" :disabled="disForm" placeholder="请输入姓名" clearable
                              @clear="getUserList()"
                              style="width: 160px;"/>
                    <!--          <el-input v-model="dataForm.identityCard" placeholder="请输入身份证号" clearable @clear="getUserList()"  style="width: 160px;"></el-input>-->
                    <el-input v-model="dataForm.mobile" :disabled="disForm" placeholder="请输入手机号码" clearable
                              @clear="getUserList()"
                              style="width: 160px;"/>
                </el-form-item>
                <el-form-item>
                    <el-button :disabled="disForm" @click="getUserList()">查询</el-button>
                </el-form-item>
            </el-form>
            <el-table :data="userList" v-loading="dataListLoading" @selection-change="handleSelectionChange"
                      ref="multipleTable" max-height="500" :disabled="disForm">
                <el-table-column type="selection" width="30"/>
                <el-table-column type="index" label="序号" width="80" align="center"/>
                <el-table-column property="realname" label="姓名" width="200"/>
                <el-table-column property="deptName" label="部门"/>
                <el-table-column property="gender" label="性别">
                    <template slot-scope="scope">
                        <el-tag v-if="parseInt(scope.row.gender)===1">男</el-tag>
                        <el-tag v-else>女</el-tag>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    :disabled="disForm"
                    @size-change="sizeChangeHandle"
                    @current-change="currentUserChangeHandle"
                    :current-page="pageIndex"
                    :page-sizes="[10, 20, 50]"
                    :page-size="pageSize"
                    :total="totalCount"
                    layout="total, sizes, prev, pager, next, jumper"
                    style="margin-top: 10px"
            ></el-pagination>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogUserVisible = false">取 消</el-button>
                <el-button type="primary" @click="selectUserSubmit" :loading="loading">确 定</el-button>
            </div>
        </el-dialog>
        <!--<train-relation v-if="trainRelationVisible" ref="trainRelation" @refreshDataList="refreshDataList"></train-relation>-->
    </el-dialog>
</template>

<script>
  import ckEditor from '@/components/ckEditor/ckEditor'
  import Vue from 'vue'
  import {treeDataTranslate} from '@/utils'
  import VueQr from 'vue-qr'
  // import TrainRelation from './train-relation'

  export default {
    components: {
      // TrainRelation,
      ckEditor,
      VueQr
    },
    data () {
      return {
        trainRelationVisible: false,
        visible: false,
        dialogUserVisible: false,
        userList: [],
        selectUserList: [],
        deptList: [],
        loading: false,
        uploadLoading: false,
        multipleSelection: [],
        dataForm: {
          id: '',
          title: '',
          entryTime: [],
          trainTime: [],
          trainTeacher: '',
          trainPlace: '',
          trainHours: '',
          courseBrief: '',
          trainType: 0,
          deptIds: [],
          userList: [],
          mainImg: '',
          mainImgUrl: [],
          trainContent: '',
          sort: 0,
          paperName: '',
          plan: [{val: ''}],
          goal: '',
          institutional: ''
        },
        disForm: false,
        deptListTreeProps: {
          multiple: true,
          checkStrictly: true,
          expandTrigger: 'hover',
          label: 'name',
          value: 'id',
          children: 'children'
        },
        actionImg: this.$http.adornUrl(`/oss/oss/upload?token=${Vue.cookie.get('token')}&client=ADMIN`),
        actionVideo: this.$http.adornUrl(`/oss/oss/uploadVideo?token=${Vue.cookie.get('token')}&client=ADMIN`),
        dataList: [],
        pageIndex: 1,
        pageSize: 50,
        totalCount: 0,
        dataListLoading: false,
        paperVisible: false,
        paperId: '',
        dataRule: {
          goal: [{required: true, message: '请填写培训目的', trigger: 'blur'}],
          institutional: [{required: true, message: '请填写组织机构', trigger: 'blur'}],
          title: [{required: true, message: '请填写培训名称', trigger: 'blur'}],
          trainTeacher: [
            {required: true, message: '请填写授课老师', trigger: 'blur'}
          ],
          trainPlace: [
            {required: true, message: '请填写培训地点', trigger: 'blur'}
          ],
          entryTime: [
            {required: true, message: '请选择培训报名时间', trigger: 'blur'}
          ],
          trainTime: [
            {required: true, message: '请选择培训时间', trigger: 'blur'}
          ],
          userList: [
            {required: true, message: '选择人员', trigger: 'blur'}
          ],
          deptIds: [
            {required: true, message: '请选择部门', trigger: 'blur'}
          ],
          mainImg: [
            {required: true, message: '封面不能为空', trigger: 'blur'}
          ]
        }
      }
    },
    mounted () {
      this.getDeptList()
    },
    props: ['refreshDataList'],
    methods: {
      init (id, status) {
        this.dataForm.id = id || 0
        this.visible = true
        this.disForm = !!status
        this.dataForm.mainImgUrl = []
        this.dataForm.plan = [{val: ''}]
        this.$nextTick(() => {
          this.$refs['ckEditor'] && this.$refs['ckEditor'].setData('')
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/train/admin/train/info/${this.dataForm.id}`),
              method: 'post'
            }).then(res => {
              if (res && res.code === 200) {
                this.dataForm = res.data
                this.dataForm.plan = res.data.plan.split('_|_').map(x => ({val: x}))
                if (res.data.deptNode) {
                  this.dataForm.deptIds = JSON.parse(res.data.deptNode)
                }
                this.dataForm.mainImgUrl = [{url: res.data.mainImgUrl}]
                this.$set(this.dataForm, 'entryTime', [
                  res.data.entryStartTime,
                  res.data.entryEndTime
                ])
                this.$set(this.dataForm, 'trainTime', [
                  res.data.trainStartTime,
                  res.data.trainEndTime
                ])
                this.$refs.ckEditor && this.$refs.ckEditor.setData(res.data.trainContent)
              }
            })
          }
        })
      },
      editorChange (val) {
        this.dataForm.trainContent = val
      },
      relattionHandle (id) {
        this.trainRelationVisible = true
        this.$nextTick(() => {
          this.$refs.trainRelation.init(id)
        })
      },
      // 获取部门列表
      getDeptList () {
        this.$http({
          url: this.$http.adornUrl('/usercenter-admin/dept/select'),
          method: 'post'
        }).then(data => {
          this.deptList = treeDataTranslate(data.data, 'id')
        })
      },

      // 获取用户列表
      getUserList () {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/usercenter-admin/user/list'),
          method: 'post',
          data: {
            realname: this.dataForm.realname,
            identityCard: this.dataForm.identityCard,
            mobile: this.dataForm.mobile,
            page: (this.dataForm.realname || this.dataForm.identityCard || this.dataForm.mobile) ? '' : this.pageIndex,
            limit: this.pageSize
          }
        }).then(res => {
          this.dataListLoading = false
          this.userList = res.data.list
          this.totalCount = res.data.totalCount
          var list = []
          for (let i = 0; i < this.userList.length; i++) {
            for (let j = 0; j < this.dataForm.userList.length; j++) {
              if (this.userList[i].userId === this.dataForm.userList[j].userId) {
                list.push(this.userList[i])
              }
            }
          }
          this.selectUserList[this.pageIndex - 1] = list

          // 用户选中状态回显
          let rows = this.selectUserList[this.pageIndex - 1]
          if (rows) {
            rows.forEach(row => {
              for (let i = 0; i < this.userList.length; i++) {
                if (row.userId === this.userList[i].userId) {
                  this.$nextTick(function () {
                    this.$refs.multipleTable.toggleRowSelection(this.userList[i])
                  })
                }
              }
            })
          }
        })
      },

      // 增加一条培训计划
      addValue () {
        this.dataForm.plan.push({val: ''})
      },
      // 删除一条培训计划
      removeValue (index) {
        this.dataForm.plan.splice(index, 1)
      },

      // 改变培训参与人员类型
      typeChange () {
        this.dataForm.userList = []
        this.dataForm.deptIds = []
      },

      // 打开用户列表弹窗
      handlerOpenUserDialog () {
        this.dialogUserVisible = true
        this.getUserList()
      },

      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getUserList()
      },

      // 用户列表翻页
      currentUserChangeHandle (val) {
        this.pageIndex = val
        this.getUserList()
      },

      // 多选用户
      handleSelectionChange (val) {
        this.multipleSelection = val
        this.selectUserList[this.pageIndex - 1] = val
      },

      // 确认选中用户
      selectUserSubmit () {
        this.selectUserList.forEach(item => {
          item.forEach(childItem => {
            this.dataForm.userList.push(childItem)
          })
        })
        this.dialogUserVisible = false
      },

      // 删除选中用户
      deleteHandle (index) {
        this.dataForm.userList.splice(index, 1)
      },

      // 表单提交
      dataFormSubmit () {
        var userIds = []
        if (this.dataForm.userList) {
          this.dataForm.userList.forEach(item => {
            userIds.push(item.userId)
          })
        }
        var deptIds = []
        if (this.dataForm.deptIds) {
          for (let i = 0; i < this.dataForm.deptIds.length; i++) {
            let idx = this.dataForm.deptIds[i].length - 1
            deptIds.push(this.dataForm.deptIds[i][idx])
          }
        }
        var that = this
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            this.loading = true
            this.$http({
              url: this.$http.adornUrl(
                `/train/admin/train/${!this.dataForm.id ? 'save' : 'update'}`
              ),
              method: 'post',
              data: {
                id: this.dataForm.id || undefined,
                title: this.dataForm.title,
                trainTeacher: this.dataForm.trainTeacher,
                trainContent: this.dataForm.trainContent,
                trainHours: this.dataForm.trainHours,
                trainPlace: this.dataForm.trainPlace,
                entryStartTime: this.dateTime(this.dataForm.entryTime[0]),
                entryEndTime: this.dateTime(this.dataForm.entryTime[1]),
                trainStartTime: this.dateTime(this.dataForm.trainTime[0]),
                trainEndTime: this.dateTime(this.dataForm.trainTime[1]),
                sort: this.dataForm.sort,
                partakeIds: this.dataForm.trainType === 1 ? deptIds : this.dataForm.trainType === 2 ? userIds : [],
                deptNode: JSON.stringify(this.dataForm.deptIds),
                courseBrief: this.dataForm.courseBrief,
                mainImg: this.dataForm.mainImg,
                trainType: this.dataForm.trainType,
                goal: this.dataForm.goal,
                plan: this.dataForm.plan ? this.dataForm.plan.map(x => x.val).join('_|_') : '',
                institutional: this.dataForm.institutional
              }
            }).then(res => {
              if (res && res.code === 200) {
                that.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    that.visible = false
                    that.$emit('refreshDataList')
                    setTimeout(function () {
                      that.$refs.ckEditor.setContent('')
                    }, 200)
                  }
                })
                this.loading = false
              } else {
                that.$message.error(res.msg)
              }
              that.loading = false
            })
          }
        })
      },

      // 上传主图
      handleImgSuccess (res, file) {
        this.uploadLoading = false
        this.dataForm.mainImg = res.data.id
      },
      beforeImgUpload (file) {
        this.uploadLoading = true
        let isJPG = file.type.split('/')[0] === 'image'
        const isLt2M = file.size / 1024 / 1024 < 2

        if (!isJPG) {
          this.$message.error('只能上传图片格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!')
        }
        return isJPG && isLt2M
      },
      handleImgRemove (file, fileList) {
        this.dataForm.mainImg = ''
        this.dataForm.mainImgUrl = []
      },

      // 上传视频
      handleVideoSuccess (res, file) {
        this.dataForm.video = res.data.id
      },
      beforeVideoUpload (file) {
        const isAVI = file.type === '/rmvb/mp4'

        if (!isAVI) {
          this.$message.error('上传视频为 /rmvb/mp4 格式!')
        }

        return isAVI
      },
      handleVideoRemove (file, fileList) {
        this.dataForm.video = ''
      },

      handleExceed () {
        this.$message.error('限制数量为：1')
      },

      // 日期转为时间戳
      dateTime (value) {
        // let val =
        //   value.toLocaleDateString().replace(/\//g, "-") +
        //   " " +
        //   value.toTimeString().substr(0, 8);
        let val = new Date(value).getTime()
        return val
      }
    }
  }
</script>

<style scoped>
    .flex-box {
        display: flex;
        justify-content: space-between;
    }
</style>
